package com.zrwl.poscloud.commons.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 文件上传工具类 (包含图片回调功能)
 *
 * @ClassName: FileUploadUtil
 * @Description: 文件上传工具类 (包含图片回调功能)
 */
public class FileUploadUtil {
    /**
     * 文件上传
     *
     * @param request
     * @param directoryName 文件上传目录：比如upload(无需带前面的/) upload/news ..
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @Title upload
     */
    public static List<Map> upload(HttpServletRequest request, String directoryName) throws IllegalStateException, IOException {
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());
        // 图片名称
        List<Map> result = new ArrayList<>();
        String fileName = null;
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 记录上传过程起始时的时间，用来计算上传时间
                // int pre = (int) System.currentTimeMillis();
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    // 取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    assert myFileName != null;
                    if (!"".equals(myFileName.trim())) {
                        // 获得文件的原始名称
                        StringBuilder originalFilename = new StringBuilder(file.getOriginalFilename());
                        // 获得文件后缀名称,判断后缀是否是文件
                        if (!originalFilename.toString().contains(".")) {
                            continue;
                        }
                        originalFilename = new StringBuilder(getFileInfoName(String.valueOf(originalFilename)));
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                        if (!AboutFileUtil.isSafe(suffix)) {
                            continue;
                        }
                        // 获得上传路径的绝对路径地址(/upload)-->
                        System.out.println(directoryName);
                        // 如果路径不存在，则创建该路径
                        File realPathDirectory = new File(directoryName);
                        if (!realPathDirectory.exists()) {
                            realPathDirectory.mkdirs();
                        }
                        ;
                        if (AboutFileUtil.isPic(suffix)) {
                            fileName = UUID.randomUUID() + "." + suffix;
                        } else {
                            fileName = String.valueOf(originalFilename);
                        }
                        Map<String, String> map = new HashMap<>();
                        map.put("size", String.valueOf(file.getSize()));
                        map.put("fileName", fileName);
                        result.add(map);
                        File uploadFile = new File(realPathDirectory + "\\" + fileName);
                        System.out.println(uploadFile);
                        file.transferTo(uploadFile);

                    }
                }
                // 记录上传该文件后的时间
                // int finaltime = (int) System.currentTimeMillis();
                // System.out.println(finaltime - pre);
            }
        }
        return result;
    }

    /**
     * 文件上传
     *
     * @param file
     * @param directoryName 文件上传目录：比如upload(无需带前面的/) upload/news ..
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @Title upload
     */
    public static List<Map> upload(MultipartFile file, String directoryName) throws IllegalStateException, IOException {
        List<Map> result = new ArrayList<>();
        // 取得上传文件
        if (file != null) {
            // 取得当前上传文件的文件名称
            String myFileName = file.getOriginalFilename();
            // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
            assert myFileName != null;
            if (!"".equals(myFileName.trim())) {
                // 获得文件的原始名称
                StringBuilder originalFilename = new StringBuilder(file.getOriginalFilename());
                // 获得文件后缀名称,判断后缀是否是文件
                originalFilename = new StringBuilder(getFileInfoName(String.valueOf(originalFilename)));
                String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                // 如果路径不存在，则创建该路径
                File realPathDirectory = new File(directoryName);
                if (!realPathDirectory.exists()) {
                    realPathDirectory.mkdirs();
                }
                String fileName = "";
                if (AboutFileUtil.isPic(suffix)) {
                    fileName = UUID.randomUUID() + "." + suffix;
                } else {
                    fileName = String.valueOf(originalFilename);
                }
                Map<String, String> map = new HashMap<>();
                map.put("size", String.valueOf(file.getSize()));
                map.put("fileName", fileName);
                result.add(map);
                File uploadFile = new File(realPathDirectory + "\\" + fileName);
                file.transferTo(uploadFile);

            }
        }
        return result;
    }

    /**
     * ckeditor文件上传功能，回调，传回图片路径，实现预览效果。
     *
     * @param request
     * @param response
     * @param directoryName 文件上传目录：比如upload(无需带前面的/) upload/..
     * @throws IOException
     * @Title ckeditor
     */
    public static void ckeditor(HttpServletRequest request, HttpServletResponse response, String directoryName)
            throws IOException {
        List<Map> list = upload(request, directoryName);
        String fileName = String.valueOf(list.get(0).get("fileName"));
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        if (!AboutFileUtil.isSafe(suffix)) {
            return;
        }
        // 结合ckeditor功能
        // imageContextPath为图片在服务器地址，如upload/123.jpg,非绝对路径
        String imgUrl = "http://localhost:8600/";
        String imageContextPath = imgUrl + "/" + directoryName + "/" + fileName;
        response.setContentType("text/html;charset=UTF-8");
        String callback = request.getParameter("CKEditorFuncNum");
        PrintWriter out = response.getWriter();
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageContextPath + "',''" + ")");
        out.println("</script>");
        out.flush();
        out.close();
    }

    private static String getFileInfoName(String value) {
        String suffix = null, name = null;
        if (value.contains(".")) {
            name = value.split("\\.")[0];
            suffix = value.split("\\.")[1];
        }
        if (name.contains("&") && name.contains("#") && name.contains(";")) {
            name = ASCIIUtils.ASCIIToConvert(name.replace(";", ",").replaceAll("[^\\d,]", ""));
        }
        String fileInfoName = name + "." + suffix;
        return fileInfoName;
    }
}

